/*
 * @Author: rock
 * @Date: 2025-05-23 17:39:42
 * @LastEditors: rock 
 * @LastEditTime: 2025-05-26 00:50:45
 * @FilePath: /002ThreadPool/main/main.cpp
 * @Description: Ctrl+Num1-> For Document; Ctrl+Num2-> For Function
 *
 * Copyright (c) 2025 by rock, All Rights Reserved.
 */

#include "threadpool.h"
using uLong = unsigned long long;
// test class MyTask
class MyTask : public Task
{
public:
    MyTask()
    {
    }
    ~MyTask()
    {
    }

    MyTask(int begin, int end)
        : begin_(begin), end_(end)
    {
    }

    // run方法最终是在线程池分配的线程中做事情
    Any run()
    {
        LOG("\tbegin, run" << "tId:" << std::this_thread::get_id());

        // 执行过程两秒
        // std::this_thread::sleep_for(std::chrono::seconds(5));

        uLong sum = 0;
        for (uLong i = begin_; i <= end_; i++)
        {
            sum += i;
        }

        LOG("\t  end, run, tId:" << std::this_thread::get_id());
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return sum;
    }

private:
    int begin_;
    int end_;
};

void sleep_for_main(int i)
{
    // main线程睡5秒等待线程池中的线程执行完毕
    LOG("main thread sleep for 5s ...");
    std::this_thread::sleep_for(std::chrono::seconds(i));
}

int main()
{
    // 创建线程池, 默认启动模式是Fixed模式, 固定线程数量的线程池
    ThreadPool pool;

    // setMode();设置线程池增长模式, 设置自增线程的线程池模式
    pool.setMode(PoolMode::MOD_FIXED);
    // pool.setMode(PoolMode::MOD_CACHED);

    // 启动线程池
    pool.start(8);

    sleep_for_main(4);

    Result res1 = pool.submitTask(std::make_shared<MyTask>(1, 100000000));
    Result res2 = pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
    Result res3 = pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
    Result res4 = pool.submitTask(std::make_shared<MyTask>(1, 300000000));

    uLong sum1 = res1.get().cast_<uLong>();
    uLong sum2 = res2.get().cast_<uLong>();
    uLong sum3 = res3.get().cast_<uLong>();
    uLong sum4 = res4.get().cast_<uLong>();

    LOG("sum = " << sum1 + sum2 + sum3);
    LOG("sum = " << sum4);

    Result res5 = pool.submitTask(std::make_shared<MyTask>(1, 300000000));

    

    uLong sum5 = res5.get().cast_<uLong>();
    LOG("最后一个线程结果: sum5 = " << sum5);


    sleep_for_main(200);

    return 0;
}